package com.nickstumpos.android.easyVolume.events.recievers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import org.apache.commons.codec.binary.Base64;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.nickstumpos.android.easyVolume.constants.EVCONSTANTS;
import com.nickstumpos.android.easyVolume.events.Dto.EventTriggerDto;
import com.nickstumpos.android.easyVolume.preset.service.PresetService;

public class ApplyPresetHeadsetReciever extends BroadcastReceiver {

	private PresetService			presetService;
	private SharedPreferences	settings;
	private boolean						read	= false;

	@Override
	public void onReceive(Context context, Intent i) {
		if (this.read) {
			this.presetService = new PresetService(context);
			this.settings = context.getSharedPreferences(EVCONSTANTS.PREFS_NAME, 0);
			int state = i.getIntExtra("state", -1);
			String old = this.settings.getString(EVCONSTANTS.EVENT_SCHED_DTO, null);
			if (old != null) {
				final byte[] buf = Base64.decodeBase64(old.getBytes());
				ObjectInputStream in = null;
				try {
					in = new ObjectInputStream(new ByteArrayInputStream(buf));
					EventTriggerDto inflated = (EventTriggerDto) in.readObject();
					if (inflated != null) {
						if (state == 0) {
							if (inflated.isHsDisconnectActive()) {
								if (inflated.getHsDisconnectPreset() != null) {
									this.presetService.applyPreset(inflated
											.getHsDisconnectPreset());
								}
							}
						} else if (state == 1) {
							if (inflated.isHsConnectActive()) {
								if (inflated.getHsConnectPreset() != null) {
									this.presetService.applyPreset(inflated.getHsConnectPreset());
								}
							}
						}
					}
				} catch (final IOException e) {
				} catch (final ClassNotFoundException e) {
				}
			}

		}
		this.read = true;
	}

}
